﻿using RestSharp;
// 需要安装Flurl和Flurl.Http

namespace _19_读取网页;

internal class Program
{
    private static async Task Main(string[] args)
    {
        #region 1_使用HttpClient读取网页

        //using var client = new HttpClient();
        //client.DefaultRequestHeaders.Add("User-Agent", "C# console program");

        // 使用异步
        //var content = await client.GetStringAsync("http://webcode.me");

        //Console.WriteLine(content);

        #endregion

        #region 2_使用WebClient读取网页

        //using var client = new WebClient();
        //client.Headers.Add("User-Agent", "C# console program");

        //string url = "http://webcode.me";
        //// // 2_1 同步读取, 会堵塞直到读取完成
        ////string content = client.DownloadString(url);
        ////Console.WriteLine(content);
        //// // 2_2 异步读取, 不会堵塞
        //client.DownloadStringCompleted += (sender, e) =>
        //{
        //    Console.WriteLine(e.Result);
        //};
        //// 下载指定为String或者Uri的资源,该方法不会堵塞调用线程,而是会返回一个任务
        //client.DownloadStringAsync(new Uri(url));

        #endregion

        #region 3_使用HttpWebRequest读取网页

        //string html = string.Empty;
        //string url = "http://webcode.me";

        //HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        //request.UserAgent = "C# console client";
        //request.Method = "GET";

        //using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
        //using (Stream stream = resp.GetResponseStream())
        //using (StreamReader reader = new StreamReader(stream))
        //{
        //    html = reader.ReadToEnd();
        //}
        //Console.WriteLine(html);

        #endregion

        #region 4_使用Flurl.Http读取网页

        //string result = await "http://webcode.me".GetStringAsync();
        //Console.WriteLine(result);

        #endregion

        #region 5_使用RestSharp读取网页

        // 创建RestClient实例
        var client = new RestClient("http://webcode.me");

        // 创建RestRequest实例，指定资源路径和方法
        var request = new RestRequest("/resource");

        // 如果需要，可以添加参数
        // request.AddParameter("name", "value");

        // 发送请求并获取响应
        var response = client.Execute(request);

        // 检查响应状态
        if (response.IsSuccessful)
            // 输出响应内容
            Console.WriteLine(response.Content);
        else
            // 输出错误信息
            Console.WriteLine("Error: " + response.ErrorMessage);

        // 防止程序立即退出
        Console.ReadLine();

        #endregion
    }
}